var provinceSelect = "";//按省份查询
var citySelect = "";//按市查询
var roadSelect = "";//按道路查询
var areaSelect = "";//按区域查询
var orgSelect = "";//维修公司

//按省份查询的下拉框
$.getProvinceName = function () {
    $.ajax({
        url: '../rds_count/getProvinceName',
        type: 'post',
        data: {
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    provinceSelect = "<div class='input-group input-group-sm'><select class='form-control' id='provinceChoose'> <option value='-1'>省份</option>";
                    var flag = 0;
                    for (var i = 0; i < msg.jsonData.length; i++) {
                        if (msg.jsonData[i] == "" || msg.jsonData[i] == null) {
                            if (flag == 0) {
                                provinceSelect += "<option value=''>未知省份</option> ";
                                flag = 1;
                            }
                        }
                        else
                            provinceSelect += "<option value='" + msg.jsonData[i] + "'>" + msg.jsonData[i] + "</option>";
                    }
                    provinceSelect += "</select></div>";
                }
            }
        }
    });
};

//按市查询的下拉框
$.getCityName = function (provinceName) {
    $.ajax({
        url: '../rds_count/getCityName',
        type: 'post',
        data: {
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId,
            provinceName: provinceName
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    citySelect = "<option value='-1'>市</option>";
                    var flag = 0;
                    for (var i = 0; i < msg.jsonData.length; i++) {
                        if (msg.jsonData[i] == "" || msg.jsonData[i] == null) {
                            if (flag == 0) {
                                citySelect += "<option value=''>未知市</option> ";
                                flag = 1;
                            }
                        }
                        else
                            citySelect += "<option value='" + msg.jsonData[i] + "'>" + msg.jsonData[i] + "</option>";
                    }
                    $("#cityChoose").html(citySelect);
                }
            }
        }
    });
};

//按区域查询的下拉框
$.getAllAreaName = function (provinceName, cityName) {
    $.ajax({
        url: '../rds_count/getAllAreaName',
        type: 'post',
        data: {
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId,
            provinceName: provinceName,
            cityName: cityName
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    areaSelect = "<option value='-1'>区域</option>";
                    var flag = 0;
                    for (var i = 0; i < msg.jsonData.length; i++) {
                        if (msg.jsonData[i] == "" || msg.jsonData[i] == null) {
                            if (flag == 0) {
                                areaSelect += "<option value=''>未知区域</option> ";
                                flag = 1;
                            }
                        }
                        else
                            areaSelect += "<option value='" + msg.jsonData[i] + "'>" + msg.jsonData[i] + "</option>";
                    }
                    $("#areaChoose").html(areaSelect);
                }
            }
        }
    });
};

//按道路查询的下拉框
$.getAllRoadName = function (provinceName, cityName, areaName) {
    $.ajax({
        url: '../rds_count/getAllRoadName',
        type: 'post',
        data: {
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId,
            provinceName: provinceName,
            cityName: cityName,
            areaName: areaName
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    roadSelect = "<option value='-1'>道路</option>";
                    var flag = 0;
                    for (var i = 0; i < msg.jsonData.length; i++) {
                        if (msg.jsonData[i] == null || msg.jsonData[i].length == 0) {
                            if (flag == 0) {
                                roadSelect += "<option value=''>未知道路</option>";
                                flag = 1;
                            }
                        }
                        else
                            roadSelect += "<option value='" + msg.jsonData[i] + "'>" + msg.jsonData[i] + "</option>";
                    }
                    $("#roadChoose").html(roadSelect);
                }
            }
        }
    });
};

//按维护单位查询的下拉框
$.getDealOrg = function () {
    $.ajax({
        url: '../rds_count/getDealOrg',
        type: 'post',
        data: {
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    orgSelect = "<div class='input-group input-group-sm'><select class='form-control' id='orgChoose'> ";
                    if (msg.jsonData.length > 1) {
                        orgSelect += "<option value='-1'>维护公司</option>";
                    }
                    if (msg.jsonData.length == 0) {
                        orgSelect += "<option value='-1'>无权限</option>";
                    }
                    for (var i = 0; i < msg.jsonData.length; i++) {
                        orgSelect += "<option value='" + msg.jsonData[i].orgId + "'>" + msg.jsonData[i].orgName + "</option>";
                    }
                    orgSelect += "</select></div>";
                    if (gUserLoginResult.orgType == 0 && msg.jsonData.length == 1) {
                        orgSelect = "<select class='form-control' id='orgChoose' style='display: none'>"
                        orgSelect += "<option value='" + msg.jsonData[0].orgId + "'>" + msg.jsonData[0].orgName + "</option></select>";
                    }
                }
            }
        }
    })
};

$(function () {
    $.getProvinceName();
    $.getDealOrg();
    gMainDT = $("#mainDataTables").DataTable({
        ajax: {
            url: "../rds_count/getRoadSignPole4DT",
            type: "POST",
            data: function (d) {
                d.userId = gUserLoginResult.userId;
                d.orgId = gUserLoginResult.orgId;
                d.search = $('#mainDataTables').DataTable().search(this.value);
            }
        },
        columns: [{
            data: "province"
        }, {
            data: "province"
        }, {
            data: "city",
            render: function (data, type, row) {
                var button = "<button class='btn btn-default btn-xs btn-flat' onclick='$.showAreaRoadSignCountModal(\"" + data + "\")'>" + data + "</button>";
                return button;
            }
        }, {
            data: "area"
        }, {
            data: "roadName"
        }, {
            data: "roadSignCount",
            render: function (data, type, row) {
                var button = "<button class='btn btn-default btn-xs btn-flat' onclick='$.showAreaRoadSignTypeModal(" + JSON.stringify(row) + ")'>" + data + "</button>";
                return button;
            }
        }, {
            data: "orgName"
        }],
        dom: "<'row'<'col-md-2'l><'#mainToolbar.col-md-10 '>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'><button type='button' class='btn btn-primary btn-sm btn-flat' style='margin-right: 5px' onclick='$.returnRoadSignCount();'><i class='glyphicon glyphicon-chevron-left'></i>返回 </button><div class='btn-group'>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>";
            strToolBar += "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false' onclick='$.dateReturn()'>";
            strToolBar += "<span class='caret'></span><span class='sr-only'>切换下拉</span></button><ul class='dropdown-menu'>";
            strToolBar += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='gMainDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button></li>";
            strToolBar += "<button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.downRoadPoleByExcel()'><i class='fa fa-download'></i> 导出信息</button></li>";
            strToolBar += "</ul></div>&nbsp;" + orgSelect + "&nbsp;" + provinceSelect + "&nbsp;" + "<div class='input-group input-group-sm'><select class='form-control' id='cityChoose'></select></div>" + "&nbsp;" +
                "<div class='input-group input-group-sm'><select class='form-control' id='areaChoose'></select></div>" + "&nbsp;<div class='input-group input-group-sm'>" +
                "<select class='form-control' id='roadChoose'></select>";
            strToolBar += "<span class='input-group-btn'><button class='btn btn-primary btn-flat' type='button' onclick='$(this).searchDT()'><i class='fa fa-search'></i></button></span></div>";
            $("#mainToolbar").append(strToolBar);
            //让时间插件正常使用
            $("#timeLimit").focus(function () {
                $('#timeLimit').daterangepicker({
                    autoUpdateInput: false,
                    locale: {
                        format: 'YYYY-MM-DD',
                        applyLabel: '确认',
                        cancelLabel: '取消',
                        fromLabel: '从',
                        toLabel: '到',
                        weekLabel: 'W',
                        customRangeLabel: 'Custom Range',
                        daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
                        monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                    }
                }).on('cancel.daterangepicker', function (ev, picker) {
                    $(this).val('');
                }).on('apply.daterangepicker', function (ev, picker) {
                    $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
                });
                $(".dropdown-menu").css("min-width", "0");
            });
            $.getCityName(-1);
            $.getAllAreaName(-1, -1);
            $.getAllRoadName(-1, -1, -1);
            //省
            $("#provinceChoose").change(function () {
                $.getCityName($("#provinceChoose").val());
                $.getAllAreaName($("#provinceChoose").val(), $("#cityChoose").val());
                $.getAllRoadName($("#provinceChoose").val(), $("#cityChoose").val(), $("#areaChoose").val());
            });
            //市
            $("#cityChoose").change(function () {
                $.getAllAreaName($("#provinceChoose").val(), $("#cityChoose").val());
                $.getAllRoadName($("#provinceChoose").val(), $("#cityChoose").val(), $("#areaChoose").val());
            });
            //区
            $("#areaChoose").change(function () {
                $.getAllRoadName($("#provinceChoose").val(), $("#cityChoose").val(), $("#areaChoose").val());
            });
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });

});

// 搜索框查询操作
$.fn.searchDT = function () {
    //在对表格进行查询时，如果没有选择值项进行查询，该变量的值就赋值为-1，在后台用特殊字符"#"进行拆分
    var provinceName = $("#provinceChoose").val();
    var cityName = $("#cityChoose").val();
    var areaName = $("#areaChoose").val();
    var roadName = $("#roadChoose").val();
    var orgChoose = $("#orgChoose").val();
    var searchContext = provinceName + "#" + cityName + "#" + areaName + "#" + roadName + "#" + orgChoose;
    gMainDT.search(searchContext).draw();
};

//使时间插件使用正常
$.dateReturn = function () {
    $(".dropdown-menu").css("min-width", "100%");
};

$.returnRoadSignCount = function () {
    $("#workbench").load("count/roadSignCount.html");
};


/*柱状图*/
var barChartOptions = {
    //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
    scaleBeginAtZero: true,
    //Boolean - Whether grid lines are shown across the chart
    scaleShowGridLines: true,
    //String - Colour of the grid lines
    scaleGridLineColor: "rgba(0,0,0,.05)",
    //Number - Width of the grid lines
    scaleGridLineWidth: 1,
    //Boolean - Whether to show horizontal lines (except X axis)
    scaleShowHorizontalLines: true,
    //Boolean - Whether to show vertical lines (except Y axis)
    scaleShowVerticalLines: true,
    //Boolean - If there is a stroke on each bar
    barShowStroke: true,
    //Number - Pixel width of the bar stroke
    barStrokeWidth: 2,
    //Number - Spacing between each of the X value sets
    barValueSpacing: 5,
    //Number - Spacing between data sets within X values
    barDatasetSpacing: 1,
    //String - A legend template
    legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
    //Boolean - whether to make the chart responsive
    responsive: true,
    maintainAspectRatio: true,
    showTooltips: false,
    onAnimationComplete: function () {
        var ctx = this.chart.ctx;
        ctx.font = this.scale.font;
        ctx.fillStyle = this.scale.textColor;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';
        this.datasets.forEach(function (dataset){
            dataset.bars.forEach(function (bar) {
                ctx.fillText(bar.value, bar.x, bar.y);
            });
        });
    }
};
barChartOptions.datasetFill = false;

//按区域统计标牌柱状图
$.showAreaRoadSignCountModal = function (city) {
    $("#label-areaRoadSignCount").text(city + "区域统计");
    $("#modal-areaRoadSignCount").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
    $('#modal-areaRoadSignCount').on('shown.bs.modal', function (e) {
        $.ajax({
            url: '../rds_count/getAreaRoadSignCount',
            type: 'post',
            data: {
                userId: gUserLoginResult.userId,
                orgId: $("#orgChoose").val(),
                roadSignCity: city
            },
            dataType: 'json',
            success: function (msg) {
                if (msg != null && typeof (msg) != "undefined") {
                    if (msg.isSuccess == true) {
                        var areaRoadSignCount = msg.jsonData;
                        var barCount = new Array(areaRoadSignCount.length);
                        var barAreaName = new Array(areaRoadSignCount.length);
                        barCount[0] = 0;
                        barAreaName[0] = "无数据";
                        var allCount = 0;
                        for (var i = 0; i < areaRoadSignCount.length; i++) {
                            barCount[i] = areaRoadSignCount[i][0];
                            barAreaName[i] = areaRoadSignCount[i][1];
                            allCount += barCount[i];
                        }
                        $("#label-areaRoadSignCount").text(city + "区域统计 " + "(标牌总数:" + allCount + ")");
                        if ($("#orgChoose").val() != -1) {
                            $("#label-areaRoadSignCount").text(city + "区域统计 " + "(标牌总数:" + allCount + ")" + $("#orgChoose").find("option:selected").text());
                        }
                        $("#barChart").remove();
                        $("#barChartParent").html("<canvas id='barChart' style='height:230px'></canvas>");
                        var areaChartData = {
                            labels: barAreaName,
                            datasets: [
                                {
                                    label: "Electronics",
                                    fillColor: "#00c0ef",
                                    strokeColor: "#00c0ef",
                                    pointColor: "rgba(210, 214, 222, 1)",
                                    pointStrokeColor: "#c1c7d1",
                                    pointHighlightFill: "#fff",
                                    pointHighlightStroke: "rgba(220,220,220,1)",
                                    data: barCount
                                }
                            ]
                        };
                        var barChartCanvas = $("#barChart").get(0).getContext("2d");
                        var barChart = new Chart(barChartCanvas);
                        var barChartData = areaChartData;
                        barChart.Bar(barChartData, barChartOptions);
                    }
                }
            }
        });
    });
};


//显示按类型分类的总数
var Json;
$.showAreaRoadSignTypeModal = function (json) {
    Json=json;
    $("#label-areaRoadSignCountBar").text("标牌类型统计  " + json.orgName + " " + json.roadName + "(" + json.roadSignCount + ")");
    $("#modal-areaRoadSignCountBar").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

$('#modal-areaRoadSignCountBar').on('shown.bs.modal', function (e) {
    $.ajax({
        url: '../rds_count/getPerSignCountsByRoad',
        type: 'post',
        data: {
            province: Json.province,
            city: Json.city,
            area: Json.area,
            orgName: Json.orgName,
            roadName: Json.roadName
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var signCounts = [0, 0, 0, 0, 0, 0, 0, 0];
                    var counts = msg.jsonData;
                    for (var i = 0; i < counts.length; i++) {
                        signCounts[counts[i]]++;
                    }
                    $("#barChart2").remove();
                    $("#barChartParent2").html("<canvas id='barChart2' style='height:230px'></canvas>");
                    var areaChartData = {
                        labels: ["警告", "禁令", "指示", "指路", "旅游", "辅助", "作业", "告示"],
                        datasets: [
                            {
                                label: "Electronics",
                                fillColor: "#00c0ef",
                                strokeColor: "#00c0ef",
                                pointColor: "rgba(210, 214, 222, 1)",
                                pointStrokeColor: "#c1c7d1",
                                pointHighlightFill: "#fff",
                                pointHighlightStroke: "rgba(220,220,220,1)",
                                data: signCounts
                            }
                        ]
                    };
                    var barChartCanvas = $("#barChart2").get(0).getContext("2d");
                    var barChart = new Chart(barChartCanvas);
                    var barChartData = areaChartData;
                    barChart.Bar(barChartData, barChartOptions);
                }
            }
        }
    });
});

$.downRoadPoleByExcel = function () {
    var provinceName = $("#provinceChoose").val();
    var cityName = $("#cityChoose").val();
    var areaName = $("#areaChoose").val();
    var roadName = $("#roadChoose").val();
    var orgChoose = $("#orgChoose").val();
    var searchContext = provinceName + "#" + cityName + "#" + areaName + "#" + roadName + "#" + orgChoose;
    var url = "../rds_count/downRoadSignByExcel?provinceName=" + provinceName + "&cityName=" + cityName + "&areaName=" + areaName +
        "&roadName=" + roadName + "&orgChoose=" + orgChoose + "&&userId=" + gUserLoginResult.userId + "&orgId=" + gUserLoginResult.orgId + "";
    window.open(url);
};